package com.example.ashmemservice;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Binder;
import android.os.IBinder;
import android.os.MemoryFile;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;

import java.io.FileDescriptor;
import java.lang.reflect.Method;


public class RemoteService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public class MyBinder extends Binder {
        @Override
        protected boolean onTransact(int code, Parcel data,
                                     Parcel reply, int flags) throws RemoteException {
            if (code == 1) {
                try {
                    String str = "kobewang";
                    Drawable drawable = getResources().getDrawable(R.mipmap.img, null);
                    Bitmap bitmap = drawableToBitmap(drawable);
                    int len = bitmap.getRowBytes() * bitmap.getHeight();
                    //创建匿名共享内存
                    MemoryFile mf = new MemoryFile("memfile", len);
                    //写入字符数据
//                    mf.writeBytes(contentBytes, 0, 0, contentBytes.length);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 0, mf.getOutputStream());

                    Method method = MemoryFile.class.getDeclaredMethod("getFileDescriptor");
                    //通过反射获得文件句柄
                    FileDescriptor fd = (FileDescriptor) method.invoke(mf);
                    ParcelFileDescriptor pfd = ParcelFileDescriptor.dup(fd);
                    //将文件句柄写到binder调用的返回值中。
                    reply.writeFileDescriptor(fd);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return super.onTransact(code, data, reply, flags);
        }
    }

    /**
     * Drawable转换成一个Bitmap
     *
     * @param drawable drawable对象
     * @return
     */
    public static final Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}
